package com.googlecode.todo_robot.frontend.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.gadgets.client.Gadget;
import com.google.gwt.gadgets.client.UserPreferences;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.googlecode.todo_robot.frontend.client.model.Todo;
import com.googlecode.todo_robot.frontend.client.service.TodoGwtService;
import com.googlecode.todo_robot.frontend.client.service.TodoGwtServiceAsync;
import com.googlecode.todo_robot.frontend.client.util.GadgetRpcUtils;
import com.googlecode.todo_robot.frontend.client.view.TodoGadgetView;

import java.util.List;

/**
 * @author Fuad Ibrahimov
 * @since 27.12.2009
 */
@Gadget.ModulePrefs(
        title = "Todo management gadget",
        directory_title = "TodoGadget - Todo management gadget",
        author = "Fuad Ibrahimov",
        author_email = "fuad@ibrahimov.de",
        height = 210,
        thumbnail = "http://todo-robot.appspot.com/toolbaricon.png", // TODO - replace with a real one
        screenshot = "http://todo-robot.appspot.com/toolbaricon.png") // TODO - replace with a real one
@Gadget.InjectModulePrefs(files = {"ModulePrefsRpc.xml", "ModulePrefsDynamicHeight.xml"})
public class TodoGadget extends Gadget<UserPreferences> {

  @Override
  protected void init(UserPreferences userPreferences) {
    final TodoGadgetView gadgetView = new TodoGadgetView();
    RootLayoutPanel.get().add(gadgetView);
    RequestBuilder requestBuilder = service.todosOf("PUT_HERE_YOUR_WAVE_ACCOUNT", new AsyncCallback<List<Todo>>() {
      @Override
      public void onFailure(Throwable throwable) {
        Window.alert(throwable.getClass().getName() + "\n" + throwable.getMessage());
      }

      @Override
      public void onSuccess(List<Todo> todos) {
        gadgetView.addTodos(todos);
      }
    });
    GadgetRpcUtils.rpcPost(requestBuilder);
  }

  private final TodoGwtServiceAsync service = (TodoGwtServiceAsync) GWT.create(TodoGwtService.class);

}
